﻿using System.Runtime.InteropServices;

namespace GraphicsSetup
{
    public class PreciseTimer
    {
        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32")]
        private static extern bool QueryPerformanceFrequency(ref long performanceFrequency);

        [System.Security.SuppressUnmanagedCodeSecurity]
        [DllImport("kernel32")]
        private static extern bool QueryPerformanceCounter(ref long performanceCount);

        readonly long _ticksPerSecond;
        long _previousElapsedTime;

        public PreciseTimer()
        {
            QueryPerformanceFrequency(ref _ticksPerSecond);
            GetElapsedTime(); // Get rid of first rubbish result
        }

        public double GetElapsedTime()
        {
            long time = 0;
            QueryPerformanceCounter(ref time);

            var elapsedTime = (double)(time - _previousElapsedTime) / _ticksPerSecond;
            _previousElapsedTime = time;

            return elapsedTime;
        }
    }
}